package persistency.reader;

/**
 * ContentReader.java
 * Purpose: serves to read a text file's contents into a collection of objects
 * 
 * @author Hans Brems
 * @version 1.0 03/11/2011
 */

import java.io.FileNotFoundException;
import java.io.FileReader;

import java.util.Scanner;
import java.util.regex.Pattern;

public abstract class ContentReader {

	private String filePath;
	private boolean header;
	private Pattern pattern;
	protected Scanner scanner;
	
	/** Aids in construction of subclasses */
	public ContentReader(){
		this.header = true;
		this.pattern = Pattern.compile("\r?\n|\t");
	}
	
	/** Aids in construction of subclasses */
	public ContentReader(String filePath){
		this();
		this.filePath = filePath;
	}
	
	/** Returns the path of the file that will be read */
	public String getFilePath() {
		return this.filePath;
	}
	
	/** Sets the path of the file that will be read */
	public void setFilePath(String filePath) {
		this.filePath = filePath;
	}
	
	/** Returns whether or not the first line is treated as a header */
	public boolean containsHeader() {
		return this.header;
	}
	
	/** Returns the pattern that is used to read the text file */
	public Pattern getPattern() {
		return this.pattern;
	}
	
	/** Sets the pattern that is used to read the text file */
	public void setPattern(Pattern pattern) {
		this.pattern = pattern;
	}
	
	/** Sets the pattern that is used to read the text file */
	public void setPattern(String regexPattern) {
		this.pattern = Pattern.compile(regexPattern);
	}
	
	/** Determines if the first line should be treated as a header */
	public void setHeader(boolean header) {
		this.header = header;
	}
	
	/**
	 * Opens a text file from file path 
	 * @throws Exception
	 * */
	public void open() throws Exception {
		try
		{
			FileReader fileReader = new FileReader(this.filePath);
			this.scanner = new Scanner(fileReader);
			this.scanner.useDelimiter(this.pattern);
		}
		catch (FileNotFoundException fnfe) {
			// file is not found
			throw new Exception ("File could not be found");
		}
		catch (Exception ex)
		{
			throw new Exception (ex.getMessage());
		}
	} 

	/** Reads the text file */
	public abstract Object read();
	
	/** Closes the text file */
	public void close() {
		if (this.scanner != null) {
			this.scanner.close();
		}
	}
}